package partie4.router;

import java.util.Hashtable;
import java.io.*;

/**
 * Classe representant une table de routage des interfaces (correspondance IP / MAC)
 */
public class RouterTable {
	
	static final String FILE_PATH = "/partie4/rout_table.txt"; //repertoire de la table	
	private Hashtable<String, String> hashRoutTable; //la table de routage
	
	/**
	 * Constructeur publique.
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public RouterTable() throws FileNotFoundException, IOException{
		this.hashRoutTable = new Hashtable<String, String>();
		readTable();		
	}
	
	/**
	 * Permet d'obtenir le mac de l'interface ayant une IP donnee.
	 * @param destIP L'IP
	 * @return L'adresse MAC
	 */
	public String getInterface(String destIP){
		return this.hashRoutTable.get(destIP);
	}
	
	/**
	 * Lire le fichier de routage et instancier la table de routage.
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private void readTable() throws FileNotFoundException, IOException{
		InputStream fis = getClass().getResourceAsStream(FILE_PATH);
		DataInputStream dia = new DataInputStream(fis);
		BufferedReader br = new BufferedReader(new InputStreamReader(dia));
		
		String line = "";
		
		while((line = br.readLine()) != null){
			int delimiterIndex = line.indexOf("*");	
			
			String ipDest = line.substring(0, delimiterIndex);
			String strInterface = line.substring(delimiterIndex + 1);
			
			this.hashRoutTable.put(ipDest, strInterface);
		}
	}
	
	/**
	 * Accesseur de hashRoutTable.
	 * @return La table de routage.
	 */
	public Hashtable<String, String> getTable(){
		return this.hashRoutTable;
	}
	
	/**
	 * Afficher le contenu de la table de routage (pour tests).
	 */
	public void displayTable(){
		try {
			RouterTable table = new RouterTable();
			for (int i = 1; i < 7; i++){
				System.out.print("IP: 192.168.0." + i);
				System.out.println(" MAC: " + table.getTable().get("192.168.0." + i));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
